package com.sky.controller.admin;

import com.sky.config.MinioConfig;
import com.sky.controller.utils.MinioUtil;
import com.sky.result.Result;
import io.minio.messages.Bucket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用调用接口")
public class CommonController {

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    @GetMapping("/bucketExists")
    public Result<Boolean> bucketExists(@RequestParam("bucketName") String bucketName) {
        return Result.success(minioUtil.bucketExists(bucketName));
    }

    @GetMapping("/makeBucket")
    public Result<Boolean> makeBucket(String bucketName) {
        return Result.success(minioUtil.makeBucket(bucketName));
    }

    @GetMapping("/removeBucket")
    public Result<Boolean> removeBucket(String bucketName) {
        return Result.success(minioUtil.removeBucket(bucketName));
    }

    @GetMapping("/getAllBuckets")
    public Result<List<Bucket>> getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return Result.success(allBuckets);
    }

    @PostMapping("/upload")
    @ApiOperation("上传接口")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return Result.success(prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
        }
        return Result.error("上传失败");
    }

    @GetMapping("/preview")
    public Result<String> preview(@RequestParam("fileName") String fileName) {
        return Result.success(minioUtil.preview(fileName));
    }

    @GetMapping("/download")
    public Result<Boolean> download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
        return Result.success(true);
    }

    @PostMapping("/delete")
    public Result<String> remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        minioUtil.remove(objName);
        return Result.success(objName);
    }
}
